package com.ml.ws.service;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

public class KeyUtil {

	private static String KEY_ALGORITHM = "RSA";
	private static String KEY_PUBLIC  = "pb";
	private static String KEY_PRIVATE  = "pr";
	private static String ENCODING = "UTF-8";
	private static Base64 encoder = new Base64();
	
	
	public static void main(String[] args) {
		
		try {
			Map<String, Object> keyMap = KeyUtil.initKey();
			
			String pubKey = getPublicKey(keyMap);
			System.out.println(pubKey);
			String priKey = getPrivateKey(keyMap);
			System.out.println(priKey);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public static Map<String, Object> initKey() throws Exception{
		KeyPairGenerator gen = KeyPairGenerator.getInstance(KEY_ALGORITHM); 
		gen.initialize(1024);
		KeyPair keyPair = gen.generateKeyPair();
		
		RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
		
		Map<String, Object> keyMap = new HashMap<String, Object>();
		keyMap.put(KEY_PUBLIC, publicKey);
		keyMap.put(KEY_PRIVATE, privateKey);
		return keyMap;
	}
	
	public static String getPublicKey(Map<String, Object> keyMap) throws Exception{
		Key key = (Key)keyMap.get(KEY_PUBLIC);
		byte[] bs = key.getEncoded();
		return new String(encryptBASE64(bs), ENCODING);
	}
	
	public static String getPrivateKey(Map<String, Object> keyMap) throws Exception{
		Key key = (Key)keyMap.get(KEY_PRIVATE);
		byte[] bs = key.getEncoded();
		return new String(encryptBASE64(bs), ENCODING);
	}
	
	public static byte[] decryptBASE64(String key) throws Exception {
		return encoder.decode(key);
	}
	
	public static byte[] encryptBASE64(byte[] bytes) throws Exception {
		return encoder.encode(bytes);
	}
}
